<template>
  <div class="app-container">
    <!-- 生产单计划管理 -->

    <div class="search-bar">
      <!-- 搜索 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="批次号" prop="parentCode">
          <el-input
            v-noSpace
            v-model="queryParams.parentCode"
            placeholder="请输入批次号"
            clearable
            class="!w-[192px]"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="客户订单号" prop="salesOrder">
          <el-input
            v-noSpace
            v-model="queryParams.salesOrder"
            placeholder="请输入客户订单号"
            clearable
            class="!w-[192px]"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="产品名称" prop="productCode">
          <el-select
            v-model="queryParams.productCode"
            placeholder="请选择产品名称"
            class="!w-[192px]"
            clearable
            filterable
            @visible-change="getProductType"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            class="!w-[192px]"
            filterable
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="item in filteredStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产日期" prop="timeScopes">
          <el-date-picker
            v-model="queryParams.timeScopes"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleQuery"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 生产单列表 -->
    <el-card shadow="never">
      <el-table v-loading="loading" :data="pageData">
        <el-table-column prop="code" label="生产单号" align="center" width="200" />
        <el-table-column prop="parentCode" label="批次号" align="center" width="200" />
        <el-table-column prop="planDate" label="生产日期" align="center" />
        <el-table-column prop="productCode" label="产品编号" align="center" />
        <el-table-column prop="productName" label="产品名称" align="center" />
        <el-table-column prop="qty" label="生产数量" align="center">
          <template #default="scope">
            <div>
              {{ scope.row.qty }}
              {{ unitFormat(scope.row.unit) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            {{ getStatusByCode(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" fixed="right" width="250" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              v-hasPerm="'sys:planOrderManage:edit'"
              link
              size="small"
              @click="handleMaintenance(scope.row)"
            >
              维护
            </el-button>
            <el-button type="primary" link size="small" @click="handelWatch(scope.row)">
              查看客户订单
            </el-button>
            <el-button
              v-if="scope.row.status < 3"
              v-hasPerm="'sys:planOrderManage:del'"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 新增/修改弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000px"
      @close="handleCloseDialog"
    >
      <el-row style="padding: 0 20px">
        <el-col :span="6">产品编号:{{ rowObj?.prodHead?.productCode }}</el-col>
        <el-col :span="6">产品名称:{{ rowObj?.prodHead?.productName }}</el-col>
        <el-col :span="6">生产日期:{{ rowObj?.prodHead?.planDate }}</el-col>
        <el-col :span="6">
          生产数量:{{ rowObj?.prodHead?.qty }}{{ unitFormat(rowObj?.prodHead?.unit) }}
        </el-col>
      </el-row>
      <el-row class="mt10">
        <el-col :span="24">
          <el-tabs
            v-model="tabActive"
            @tab-change="handleTabChange"
            :tab-position="tabPosition"
            class="demo-tabs h100"
          >
            <el-tab-pane label="工序维护">
              <div class="df-fe">
                <p class="mr10">以下列表顺序可以拖动</p>
                <el-button
                  type="warning"
                  size="small"
                  v-hasPerm="'sys:planOrderManage:edit'"
                  @click="handleAddRow"
                >
                  新增
                </el-button>
              </div>
              <el-row>
                <div class="draggable" style="width: 100%">
                  <el-table :data="rowData" row-key="id" class="w100" @row-click="rowDrop">
                    <el-table-column type="index" label="生产顺序" align="center" width="100" />
                    <el-table-column prop="processName" label="工序名称" align="center" />
                    <el-table-column
                      label="当前生产单工序产能(回车生效)"
                      align="center"
                      width="300"
                    >
                      <template #default="scope">
                        <el-input
                          v-noSpace
                          v-model="scope.row.capacity"
                          clearable
                          size="small"
                          @keyup.enter="handleCapacityChange(scope.$index, scope.row)"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right" width="100" align="center">
                      <template #default="scope">
                        <el-button
                          type="danger"
                          size="small"
                          v-hasPerm="'sys:planOrderManage:edit'"
                          link
                          @click="handleRowDel(scope.row)"
                        >
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="生产日期维护">
              <p>计划生产日期（更改即生效）</p>
              <el-date-picker
                v-model="planDate"
                type="date"
                placeholder="请选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                @change="handleChangePlanDate"
              />
            </el-tab-pane>
            <el-tab-pane label="原材料需求">
              <el-row>
                <el-table :data="qtyData" class="w100">
                  <el-table-column prop="productName" label="原材料名称" align="center" />
                  <el-table-column prop="dosageQty" label="原材料总需求量" align="center">
                    <template #default="scope">
                      <div>
                        {{ scope.row.dosageQty }}
                        {{ unitFormat(scope.row.unit) }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="currentQty" label="库存可用原材料数量" align="center">
                    <template #default="scope">
                      <div>
                        {{ scope.row.currentQty }}
                        {{ unitFormat(scope.row.unit) }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="purchaseQty" label="需新采购原材料数量" align="center">
                    <template #default="scope">
                      <div>
                        {{ scope.row.purchaseQty }}
                        {{ unitFormat(scope.row.unit) }}
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="工人需求">
              <h1>不满足生产需求</h1>
              <p>产线工人总需求人数：{{ rowObj?.workerList?.personPlan || 0 }}</p>
              <p>生产日期当日可上班人数：{{ rowObj?.workerList?.workerTotal || 0 }}</p>
            </el-tab-pane>

            <el-tab-pane label="设备需求">
              <eqptRequire
                :processes="machineList"
                v-if="tabActive == '4'"
                @update:check-equipment="handleCheckEquipment"
              />
            </el-tab-pane>
            <el-tab-pane label="净框需求">
              洁净筐总需求量：{{ rowObj?.boxList?.boxCount || 0 }}
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer df-fe">
          <p class="mr20">备注：请确认完以上维护和需求再点击确认计划</p>
          <el-button type="primary" @click="handleSubmit()">确认计划</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核 -->
    <el-dialog
      v-model="dialogApp.visible"
      :title="dialogApp.title"
      width="500px"
      @close="handleCloseDialogApp"
    >
      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click="handlePass('pass')">通 过</el-button>
          <el-button @click="handlePass('noPass')">拒绝</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 订单编号 -->
    <el-dialog
      v-model="dialogOrder.visible"
      :title="dialogOrder.title"
      width="75%"
      @close="handleCloseDialogOrder"
    >
      <el-table ref="multipleTable" :data="dialogData">
        <el-table-column prop="code" label="订单编号" width="200" />
        <el-table-column prop="docType" label="订单类别">
          <template #default="scope">
            <span>
              {{ getDocTypeLabel(scope.row.docType) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="companyCode" label="客户编号" align="center" width="110" />
        <el-table-column prop="customerName" label="客户名称" align="center" width="160" />
        <el-table-column prop="contractCode" label="归属合同" align="center" width="110" />
        <el-table-column prop="salesMan" label="业务员" align="center" width="110">
          <template #default="scope">
            {{
              optionsSalesMan.filter((item) => item.value.toString() == scope.row.salesMan)[0]
                ?.label
            }}
          </template>
        </el-table-column>
        <el-table-column prop="createName" label="创建人" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center" width="190" />
        <el-table-column prop="deliveryDate" label="送货日期" align="center" width="110" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <span :style="{ color: getStatusColor(scope.row.status) }">
              {{ getStatusByCode(scope.row.status) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />
      </el-table>
    </el-dialog>

    <!-- 新增 -->
    <el-dialog
      v-model="dialogAdd.visible"
      :title="dialogAdd.title"
      width="500px"
      @close="handleCloseDialogAdd"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogParams"
        :inline="true"
        label-width="150px"
        :rules="rules"
      >
        <el-form-item label="工序名称" prop="processName">
          <el-select
            v-model="dialogParams.processName"
            placeholder="请选择工序名称"
            style="width: 250px"
            clearable
            filterable
            @change="changeName"
            @visible-change="getName"
          >
            <el-option
              v-for="item in optionsName"
              :key="item.value"
              :label="item.label"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="产能（天）" prop="capacity">
          <el-input-number
            v-model="dialogParams.capacity"
            disabled
            placeholder="请输入产能"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click="sumbitDialogParams">确 定</el-button>
          <el-button @click="dialogAdd.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import planOrderApi, {
  planManagePageVO,
  planOrderPageQuery,
} from "@/api/planManage/planOrderManage";
import configApi, { ConfigType } from "@/api/config/config";
import type { TabsInstance } from "element-plus";
import eqptRequire from "./components/eqptRequire.vue";
import Sortable from "sortablejs";
import { useRoute } from "vue-router";
import { nextTick } from "vue";
import UserAPI from "@/api/system/user";

//tab
const tabActive = ref("0");

//设备需求列表
const machineList = ref<any[]>([]);

const route = useRoute();
const queryCode = ref<string | undefined>(undefined);

const dialogFormRef = ref(ElForm);

const dialogParams = reactive({
  processCode: "",
  processName: "",
  capacity: 0,
});
// 新增弹窗
const dialog = reactive({
  title: "",
  visible: false,
  type: "",
});

// 订单
const dialogOrder = reactive({
  title: "",
  visible: false,
  type: "",
});

const dialogData = ref<any>();
//审核意见
const dialogApp = reactive({
  title: "审核意见",
  visible: false,
});
//新增
const dialogAdd = reactive({
  title: "",
  visible: false,
});
const approvedRemake = ref("");

defineOptions({
  name: "User",
  inheritAttrs: false,
});
const tabPosition = ref<TabsInstance["tabPosition"]>("left");
const prodLine = ref([
  {
    value: "",
    label: "",
  },
]);

const rowData = ref<any[]>([]);
const qtyData = ref<any[]>([]);

const planDate = ref("");

//生产单列表
const prodLevels = reactive([
  {
    label: "一级",
    value: "一级",
  },
  {
    label: "二级",
    value: "二级",
  },
]);
//生产单类别
const prodTypes = reactive([
  {
    label: "生产计划",
    value: "生产计划",
  },
  {
    label: "生产指令",
    value: "生产指令",
  },
]);
//单位列表
const units = reactive([
  {
    label: "个",
    value: "个",
  },
  {
    label: "斤",
    value: "斤",
  },
]);

//产品列表 potato carrot beef
const productList = ref<
  {
    codeName: string;
    codeValue: string;
  }[]
>([]);
const getProductName = () => {
  configApi.getConfigListByType(ConfigType.PROD_CODE).then((res) => {
    console.log(res);
    productList.value = res;
  });
};
// const getProductNameByCode = (code: string) => {
//   return productList.value.find((item) => item.codeValue === code)?.codeName;
// };

//状态列表
const statusList = ref<
  {
    value: number;
    label: string;
  }[]
>([]);
const getStatusList = () => {
  configApi.getConfigListByType(ConfigType.PROD_HEAD).then((res) => {
    statusList.value = [
      { value: 0, label: "待审核" },
      { value: 1, label: "已审核" },
      { value: 2, label: "审核拒绝" },
      { value: 3, label: "准备中" },
      { value: 4, label: "待生产" },
      { value: 5, label: "生产中" },
      { value: 6, label: "生产完成" },
    ];
  });
};
// const filteredStatusList = computed(() => {
//   return statusList.value.filter((item) => item.codeValue !== "1");
// });
const filteredStatusList = ref([
  { value: 0, label: "待审核" },
  { value: 1, label: "已审核" },
  { value: 2, label: "审核拒绝" },
  { value: 3, label: "准备中" },
  { value: 4, label: "待生产" },
  { value: 5, label: "生产中" },
  { value: 6, label: "生产完成" },
]);
const statusMap = {
  // 0: { label: "未提交", color: "purple" },
  1: { label: "待审核", color: "red" },
  2: { label: "审核拒绝", color: "gray" },
  3: { label: "已审核", color: "blue" },
  4: { label: "计划完成", color: "green" },
  5: { label: "生产完成", color: "cyan" },
  6: { label: "交付完成", color: "black" },
  // 7: { label: "取消订单", color: "orange" },
  // 8: { label: "取消待审核", color: "orange" },
};

const getStatusByCode = (code: string) => {
  // 将 code 转换为 number 类型进行比较
  const statusValue = Number(code);
  return statusList.value.find((item) => item.value == statusValue)?.label;
};

const queryFormRef = ref(ElForm);
const roleFormRef = ref(ElForm);
const rowObj = ref<{
  prodHead?: {
    productCode?: string;
    productName?: string;
    planDate?: string;
    qty?: string;
    unit?: string;
  };
  bomList?: {
    dosageQty?: string;
  };
  workerList?: {
    personPlan?: number;
    workerTotal?: number;
  };
  boxList?: {
    boxCount?: number;
  };
}>({});
const queryParams = reactive<planOrderPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const rowInfo = ref<any>({});

//审核弹窗id
const applyId = ref(0);

const pageData = ref<planManagePageVO[]>();

const options = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const optionsName = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const total = ref(0);
const loading = ref(false);

// 新增/修改form
let dialogFormData = reactive<planManagePageVO>({
  code: "", // 生产单编号
  prodType: "", //生产单类别
  prodLevel: "", //生产单级别
  productName: "", //产品名称
  qty: 0, //数量
  unit: "", // 单位
  deliveryDate: "", // 预计交货日期
  planDate: "", // 生产单日期
  prodLine: "", // 生产线
  remark: "", // 备注
});

const rules = reactive({
  processName: [{ required: true, message: "工序名称是必填项", trigger: "change" }],
  capacity: [{ required: true, message: "请输入产能", trigger: "blur" }],
});

// 查询
function handleQuery() {
  loading.value = true;
  console.log("queryParams", queryParams);
  //queryParams.status转为数字数组发送
  queryParams.statusList = queryParams.status ? [Number(queryParams.status)] : [0, 2];

  planOrderApi
    .getPage(queryParams)
    .then((data: any) => {
      pageData.value = [...(data.list as any)];
      console.log("data", data);
      total.value = data.total;
    })
    .catch((err) => {
      console.log(err);
      // ElMessage.error(`${err}`);
      // handleCloseDialog();
      // handleResetQuery();
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  //todo

  handleQuery();
}
//同步修改设备
const handleCheckEquipment = (checkEquipment: { id: number; eqptCode: string }) => {
  console.log(
    checkEquipment.id,
    checkEquipment.eqptCode,
    "checkEquipment.id, checkEquipment.eqptCode"
  );
  planOrderApi.editCapacity(checkEquipment).then((data: any) => {
    ElMessage.success("同步修改设备成功");
  });
};

//修改tab栏
const handleTabChange = (tab: any) => {
  tabActive.value = tab;
};

//打开审核弹窗
function handleApproved(id: number, status: number) {
  if (status == 2) {
    planOrderApi
      .approvalTProdHead({
        id,
        status: 0,
        remark: approvedRemake.value,
      })
      .then((data: any) => {
        console.log(data, "审核data");
        ElMessage.success("审核成功");
      })
      .catch((err) => {
        console.log(err);
        // ElMessage.error(`${err}`);
        // handleCloseDialog();
        handleResetQuery();
      })
      .finally(() => {
        handleQuery();
      });
  } else {
    console.log("id", id);
    dialogApp.visible = true;
    applyId.value = id as number;
  }
}

const handlePass = (type: "sub" | "pass" | "noPass") => {
  let map = {
    sub: 0, // "已提交",
    pass: 1, // "已审核",
    noPass: 2, // "已拒绝",
  };
  planOrderApi
    .approvalTProdHead({
      id: applyId.value,
      status: map[type],
      remark: approvedRemake.value,
    })
    .then((data: any) => {
      console.log(data, "审核data");

      if (type === "pass") {
        ElMessage.success("审核成功");
      } else {
        ElMessage.error("拒绝通过");
      }
    })
    .catch((err) => {
      console.log(err);
      // ElMessage.error(`${err}`);
      // handleCloseDialog();
      handleResetQuery();
    })
    .finally(() => {
      handleQuery();
      dialogApp.visible = false;
    });

  //关闭对话框，无论操作是否成功
};

/**
 * 删除生产单
 *
 * @param id
 */
function handleDelete(id: number) {
  ElMessageBox.confirm("确认删除计划?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      planOrderApi
        .deleteById(id)
        .then((data) => {
          ElMessage.success("删除成功");

          handleQuery();
        })
        .catch((err) => {
          console.log(err);
          // ElMessage.error(`${err}`);
          handleQuery();
        })
        .finally(() => {
          handleQuery();
          loading.value = false;
        });
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

function handleMaintenance(row: any) {
  rowInfo.value = { ...row };
  serviceRow(row);
}

function handelWatch(row: any) {
  dialogOrder.visible = true;
  const params = { codeList: [] };
  if (row) {
    if (row?.salesOrderCodes) {
      params.codeList = row.salesOrderCodes.split(","); // 将字符串拆分成数组
    }
  }
  planOrderApi
    .getDialogPage(params)
    .then((data) => {
      dialogData.value = [...(data?.list as any)];
    })
    .finally(() => {});
}

async function serviceRow(row: any) {
  dialog.visible = true;
  tabActive.value = "0";
  try {
    const data = await planOrderApi.getRowService(row?.id);
    rowObj.value = { ...data };
    rowData.value = [...data?.borList];
    qtyData.value = [...data?.bomList];
    console.log(qtyData, "qtyData");
    planDate.value = data?.prodHead?.planDate;
    machineList.value = data?.machineList;
    console.log(machineList.value, "machineList");

    // 确保 DOM 更新后再调用 rowDrop
    await nextTick();
    rowDrop();
  } catch (err) {
    // ElMessage.error(`${err}`);
  } finally {
    loading.value = false;
  }
}

function clearFormData() {
  let data = {
    code: "", // 生产单编号
    prodType: "", //生产单类别
    prodLevel: "", //生产单级别
    productName: "", //产品名称
    productCode: "", //产品编码
    qty: 0, //数量
    unit: "", // 单位
    deliveryDate: "", // 预计交货日期
    planDate: "", // 生产单日期
    prodLine: "", // 生产线
    remark: "", // 备注
  };
  Object.assign(dialogFormData, data);
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  // roleFormRef.value.clearValidate();
  // roleFormRef.value.resetFields();
  clearFormData();
}

function handleCloseDialogOrder() {
  dialogOrder.visible = false;
  // roleFormRef.value.clearValidate();
  // roleFormRef.value.resetFields();
}

function handleCloseDialogAdd() {
  dialogAdd.visible = false;
  // roleFormRef.value.clearValidate();
  // roleFormRef.value.resetFields();
}
// 关闭审核弹窗

function handleCloseDialogApp() {
  dialogApp.visible = false;
  //清空审核弹窗数据
  approvedRemake.value = "";
}

// 提交
function handleSubmit() {
  planOrderApi
    .sumbitCode({ prodCode: rowInfo.value.code })
    .then((data: any) => {
      ElMessage.success("提交成功");
      dialog.visible = false;
      handleQuery();
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    })
    .finally(() => {});
}

function changeProduct(val: any) {
  queryParams.productCode = val.value;
  queryParams.productName = val.label;
  if (!val.value) {
    queryParams.productCode = "";
  }
}
const getProductType = () => {
  planOrderApi
    .getTypePage({ pageNum: 1, pageSize: 20 })
    .then((data) => {
      options.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.productName,
      }));
    })
    .finally(() => {
      loading.value = false;
    });
};

const getName = () => {
  planOrderApi
    .getName({ pageNum: 1, pageSize: 999 })
    .then((data) => {
      optionsName.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.name,
        capacity: item.capacity,
      }));
    })
    .finally(() => {});
};

function changeName(val: any) {
  dialogParams.processCode = val.value;
  dialogParams.processName = val.label;
  dialogParams.capacity = val.capacity;
}

function handleRowDel(row: any) {
  ElMessageBox.confirm("确认删除该工序?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      planOrderApi
        .delCapacity({ id: row?.id })
        .then((data) => {
          ElMessage.success("操作成功");
          serviceRow(rowInfo.value);
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
        })
        .finally(() => {});
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

// 在拖拽结束处理中添加检查
const rowDrop = () => {
  const tbody = document.querySelector(".draggable .el-table__body-wrapper tbody");
  if (!tbody) return;
  console.log(tbody, "draggable");
  Sortable.create(tbody as HTMLElement, {
    draggable: ".draggable .el-table__row",
    onEnd: async ({ newIndex, oldIndex }) => {
      console.log(newIndex, "newIndex", oldIndex, "oldIndex");
      if (rowData.value && newIndex !== undefined && oldIndex !== undefined) {
        try {
          // 调用异步的 drag 方法
          await drag(rowData.value[oldIndex].id, rowData.value[newIndex].sortSeq);
          ElMessage.success("操作成功");
          serviceRow(rowInfo.value);
        } catch (err) {
          // ElMessage.error(`${err}`);
        }
      } else {
        console.warn("rowData.value is undefined or indices are invalid");
      }
    },
  });
};

// 定义异步的 drag 方法
const drag = async (id: any, sortSeq: any) => {
  return planOrderApi.drag({ id, sortSeq });
};

function handleCapacityChange(index: number, row: any) {
  // 在这里可以添加保存或其他逻辑
  console.log(`Capacity changed for row ${index}:`, row);

  planOrderApi
    .editCapacity({ id: row?.id, capacity: row?.capacity })
    .then((data) => {
      ElMessage.success("操作成功");
      serviceRow(rowInfo.value);
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleChangePlanDate(val: any) {
  if (val && rowInfo.value && rowInfo.value.id) {
    planOrderApi
      .editPlanDate({ id: rowInfo.value.id, planDate: planDate.value })
      .then((data) => {
        ElMessage.success("操作成功");
        serviceRow(rowInfo.value);
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      })
      .finally(() => {});
  }
}

const docTypeMap = {
  0: { label: "周期订单" },
  1: { label: "紧急订单" },
};

function getDocTypeLabel(status: number) {
  return docTypeMap[status as keyof typeof docTypeMap]?.label || "未知状态";
}
const optionsSalesMan = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const getSalesMan = () => {
  UserAPI.getPage({ pageNum: 1, pageSize: 999, roleName: "salesMan" }).then((data) => {
    optionsSalesMan.value = data.list.map((item: any) => ({
      value: item.id,
      label: item.name,
    }));
  });
};

function getStatus(status: number) {
  return statusMap[status as keyof typeof statusMap]?.label || "未知状态";
}

function getStatusColor(status: number) {
  return statusMap[status as keyof typeof statusMap]?.color || "未知状态";
}

function handleAddRow() {
  dialogAdd.visible = true;
  dialogAdd.title = "新增工序";
  dialogParams.processCode = "";
  dialogParams.processName = "";
  dialogParams.capacity = 0;
}

function sumbitDialogParams() {
  dialogFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    planOrderApi
      .addCapacity({ processCode: dialogParams.processCode, parentCode: rowInfo.value?.code })
      .then((data) => {
        ElMessage.success("操作成功");
        serviceRow(rowInfo.value);
        dialogAdd.visible = false;
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      })
      .finally(() => {
        loading.value = false;
      });
  });
}
// 单位常量列表
const unitOptions = ref<Array<{ label: string; value: string }>>([]);
// 获取常量列表
const getUnitList = () => {
  configApi.getConfigListByType(ConfigType.Unit).then((data) => {
    unitOptions.value = data.map((item: any) => {
      return { label: item.codeName, value: item.codeValue };
    });
  });
};
const unitFormat = (unit: any) => {
  console.log(unit, "unit");
  if (!unit) return;
  let unitLabel = unitOptions.value.find((item) => item.value === unit.toLowerCase())?.label;
  return unitLabel;
};
onMounted(() => {
  // 获取查询参数中的 queryCode
  queryCode.value = route.query.queryCode as string | undefined;
  console.log(queryCode.value, "queryCode");
  queryParams.parentCode = queryCode.value ? queryCode.value : "";
  getProductName();
  getStatusList();
  handleQuery();
  getUnitList();
  getSalesMan();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
